Conditional Sections

You can control aspects of the XML processing using conditional sections.  Conditional sections are sections that are either processed (included) by the XML processor, or ignored entirely.  There are two new keywords that you need to be aware of: INCLUDE and IGNORE.  The syntax for both is:

<![INCLUDE [ markup to include ]]>
<![IGNORE  [ markup to ignore  ]]>

A good example of when to use conditional sections is in your DTD’s.  For example, let’s say that you want to have different versions of the same DTD for different purposes.  You could do this using conditional sections.  Let’s look at the following markup:

<!-- Version 1 -->
<![INCLUDE [
	<!ENTITY % employees.body "employee+">
	<!ENTITY % employee.body "name, position, address, phone">
	<!ENTITY % name.body "first, last">
	<!ENTITY % address.body "street?, city?, state?, zip?">
	<!ENTITY % phone.body "main, office*, fax*, mobile*, home*">

	<!ELEMENT employees ( %employees.body; )>
	<!ELEMENT employee ( %employee.body; )>
	<!ELEMENT name ( %name.body; )>
	<!ELEMENT address ( %address.body; )>
	<!ELEMENT phone ( %phone.body; )>
]]>

<!-- Version 2 -->
<![IGNORE [
	<!ELEMENT employees (employee+)>
	<!ELEMENT employee (name, position, address, phone)>
	<!ELEMENT name (first, last)>
	<!ELEMENT address (street?, city?, state?, zip?)>
	<!ELEMENT phone (main, office*, fax*, mobile*, home*)>
]]>

<!ATTLIST employee id ID #REQUIRED>

<!ELEMENT first (#PCDATA)>
<!ELEMENT last  (#PCDATA)>

<!ELEMENT position (#PCDATA)>

<!ELEMENT street (#PCDATA)>
<!ELEMENT city   (#PCDATA)>
<!ELEMENT state  (#PCDATA)>
<!ELEMENT zip    (#PCDATA)>

<!ELEMENT main   (#PCDATA)>
<!ELEMENT office (#PCDATA)>
<!ELEMENT fax    (#PCDATA)>
<!ELEMENT mobile (#PCDATA)>
<!ELEMENT home   (#PCDATA)>

File: Chapter 6\Employees3.dtd

We can swap between either version of the DTD by swapping the keywords INCLUDE and IGNORE in the tags.  Better yet, we could create a couple of parameter entities that will do it for us.

<!ENTITY % ver1 "INCLUDE">
<!ENTITY % ver2 "IGNORE">

<![%ver1; [
	. . . (omitted)
]]>

<![%ver2; [
	. . . (omitted)
]]>

To change between the two versions, we simply change the values of the parameter entities.  Using this technique, we can create powerful DTD’s that can have different content models based on the situation.